package org.jeecg.modules.param.member.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.micrometer.core.instrument.util.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.bicycle.order.entity.BikeVehicleOrder;
import org.jeecg.modules.bicycle.order.mapper.BikeVehicleOrderMapper;
import org.jeecg.modules.constant.BikeConstant;
import org.jeecg.modules.param.member.entity.BikeMemberCardLog;
import org.jeecg.modules.param.member.entity.BikeMemberUser;
import org.jeecg.modules.param.member.entity.BikeMemberUserCard;
import org.jeecg.modules.param.member.mapper.BikeMemberCardLogMapper;
import org.jeecg.modules.param.member.mapper.BikeMemberUserCardMapper;
import org.jeecg.modules.param.member.mapper.BikeMemberUserMapper;
import org.jeecg.modules.param.member.service.IBikeMemberUserCardService;
import org.jeecg.modules.utils.MD5Utils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * @Description: IC卡管理
 * @Author: 月月鸟
 * @Date: 2021-05-25
 * @Version: V1.0
 */
@Service
public class BikeMemberUserCardServiceImpl extends ServiceImpl<BikeMemberUserCardMapper, BikeMemberUserCard> implements IBikeMemberUserCardService {

    @Resource
    private BikeMemberUserCardMapper bikeMemberUserCardMapper;
    @Resource
    private BikeMemberUserMapper bikeMemberUserMapper;
    @Resource
    private BikeVehicleOrderMapper bikeVehicleOrderMapper;
    @Resource
    private BikeMemberCardLogMapper bikeMemberCardLogMapper;

    @Override
    public List<BikeMemberUserCard> selectByMainId(String mainId) {
        return bikeMemberUserCardMapper.selectByMainId(mainId);
    }


    //发卡
    @Override
    public Result<?> issuance(BikeMemberUserCard bikeMemberUserCard) {
        //通过用户id查询卡表
        QueryWrapper<BikeMemberUserCard> userCardQueryWrapper = new QueryWrapper<>();
        userCardQueryWrapper.eq("user_id", bikeMemberUserCard.getUserId());
        BikeMemberUserCard memberUserCard = bikeMemberUserCardMapper.selectOne(userCardQueryWrapper);

        //校验cardNumber
        if (StringUtils.isEmpty(bikeMemberUserCard.getCardNumber())) {
            return Result.error("卡No为空");
        } else {
            int length = bikeMemberUserCard.getCardNumber().length();
            if (length != 6) {
                return Result.error("卡No长度为6位,请检查No号");
            }
            Integer selectCount = bikeMemberUserCardMapper.selectCount(new QueryWrapper<BikeMemberUserCard>().eq("card_number", bikeMemberUserCard.getCardNumber()));
            if (selectCount != 0) {
                return Result.error("卡No重复");
            }
        }

        //用户数据
        BikeMemberUser memberUserData = bikeMemberUserMapper.selectById(bikeMemberUserCard.getUserId());
        if (StringUtils.isEmpty(memberUserData.getIdCard())) {
            return Result.error("请先实名");
        }
        //判断是否充值
        if (bikeMemberUserCard.getPay() != null) {
            memberUserData.setBalance(memberUserData.getBalance().add(bikeMemberUserCard.getPay()));
            bikeMemberUserMapper.updateById(memberUserData);
            // TODO: 2021/9/11 存充值表
        }
        //判断信息是否存在
        if (memberUserCard != null) {
            return Result.error("用户有卡，请换卡！");
        } else {
            //查询卡是否入库
            QueryWrapper<BikeMemberUserCard> cardQueryWrapper = new QueryWrapper<>();
            cardQueryWrapper.eq("card_code", bikeMemberUserCard.getCardCode());
            BikeMemberUserCard cardData = bikeMemberUserCardMapper.selectOne(cardQueryWrapper);
            //判断是否有卡
            if (cardData == null) {
                BikeMemberUserCard userCard = new BikeMemberUserCard();
                userCard.setCardCode(bikeMemberUserCard.getCardCode());
                userCard.setUserId(bikeMemberUserCard.getUserId());
                userCard.setCardFee(bikeMemberUserCard.getCardFee());
                userCard.setCardStatus(BikeConstant.card_status_normal);
                userCard.setUserType(BikeConstant.member_type_user);
                userCard.setCardNumber(bikeMemberUserCard.getCardNumber());
                //设置卡类型  1 普通 2 管理 3 运维
                userCard.setCardType("1");
                bikeMemberUserCardMapper.insert(userCard);
            } else {
                if (StringUtils.isNotEmpty(cardData.getUserId())) {
                    return Result.error("此卡已被用户绑定");
                } else {
                    BikeMemberUser memberUser = new BikeMemberUser();
                    memberUser.setId(bikeMemberUserCard.getUserId());
                    //绑定卡后 改为ic卡类型用户
                    memberUser.setRegisterType(BikeConstant.register_type_ic);
                    bikeMemberUserMapper.updateById(memberUser);

                    //修改IC卡信息
                    cardData.setCardFee(bikeMemberUserCard.getCardFee());
                    cardData.setUserId(bikeMemberUserCard.getUserId());
                    cardData.setCardStatus(BikeConstant.card_status_normal);
                    cardData.setUserType(BikeConstant.member_type_user);
                    cardData.setCardNumber(bikeMemberUserCard.getCardNumber());
                    //设置卡类型  1 普通 2 管理 3 运维
                    cardData.setCardType("1");
                    bikeMemberUserCardMapper.updateById(cardData);
                }
            }
            //发卡日志
            BikeMemberCardLog bikeMemberCardLog = new BikeMemberCardLog();
            bikeMemberCardLog.setUserId(memberUserData.getId());//用户id
            bikeMemberCardLog.setCardCode(bikeMemberUserCard.getCardCode());//卡号
            bikeMemberCardLog.setCardNumber(bikeMemberUserCard.getCardNumber());//卡no号
            bikeMemberCardLog.setOperateType(1);//操作类型
            bikeMemberCardLog.setCardDeposit(bikeMemberUserCard.getCardFee());//押金
            bikeMemberCardLog.setCardFee(bikeMemberUserCard.getDeposit());//卡费
            bikeMemberCardLog.setAccount(bikeMemberUserCard.getPay());//发生额 充值金额
            bikeMemberCardLog.setCardType("1");
            bikeMemberCardLogMapper.insert(bikeMemberCardLog);

            return Result.OK("发卡成功！");

        }
    }

    //换卡
    @Override
    public Result<?> changeCard(BikeMemberUserCard bikeMemberUserCard) {
        BigDecimal cardFee = bikeMemberUserCard.getCardFee();

        //校验cardNumber
        if (StringUtils.isEmpty(bikeMemberUserCard.getNewCard().getCardNumber())) {
            return Result.error("卡No为空");
        } else {
            int length = bikeMemberUserCard.getNewCard().getCardNumber().length();
            if (length != 6) {
                return Result.error("卡No长度为6位,请检查No号");
            }
            Integer selectCount = bikeMemberUserCardMapper.selectCount(new QueryWrapper<BikeMemberUserCard>().eq("card_number", bikeMemberUserCard.getNewCard().getCardNumber()));
            if (selectCount != 0) {
                return Result.error("卡No重复");
            }
        }

        if (bikeMemberUserCard.getNewCard() == null) {
            //判断是否有卡
            return Result.error("新IC卡为空！");
        }
        if (bikeMemberUserCard.getCardCode() == null) {
            return Result.error("会员名下无卡，请发卡！");
        } else {
            //判断新卡是否存在库中
            QueryWrapper<BikeMemberUserCard> cardQueryWrapper = new QueryWrapper<>();
            cardQueryWrapper.eq("card_code", bikeMemberUserCard.getNewCard().getCardCode());
            BikeMemberUserCard cardData = bikeMemberUserCardMapper.selectOne(cardQueryWrapper);
            if (cardData == null) {
                //判断是否有卡
                BikeMemberUserCard memberUserCard = new BikeMemberUserCard();
                memberUserCard.setCardCode(bikeMemberUserCard.getNewCard().getCardCode());
                memberUserCard.setUserId(bikeMemberUserCard.getUserId());
                memberUserCard.setCardFee(bikeMemberUserCard.getCardFee());
                memberUserCard.setCardStatus(BikeConstant.card_status_normal);
                memberUserCard.setUserType(BikeConstant.member_type_user);
                memberUserCard.setCardNumber(bikeMemberUserCard.getNewCard().getCardNumber());
                //设置卡类型  1 普通 2 管理 3 运维
                memberUserCard.setCardType("1");
                bikeMemberUserCardMapper.insert(memberUserCard);
            } else {
                //判断新卡是否有用户在使用
                if (StringUtils.isNotEmpty(cardData.getUserId())) {
                    return Result.error("此卡已被用户绑定");
                }
                cardData.setCardFee(cardFee);
                cardData.setUserId(bikeMemberUserCard.getUserId());
                cardData.setCardStatus(BikeConstant.card_status_normal);
                cardData.setUserType(BikeConstant.member_type_user);
                //设置卡类型  1 普通 2 管理 3 运维
                cardData.setCardType("1");
                cardData.setCardNumber(bikeMemberUserCard.getCardNumber());

                //修改新卡信息
                bikeMemberUserCardMapper.updateById(cardData);
            }
            //换卡日志
            BikeMemberCardLog cardLog = new BikeMemberCardLog();
            cardLog.setUserId(bikeMemberUserCard.getUserId());//用户id
            cardLog.setCardCode(bikeMemberUserCard.getNewCard().getCardCode());//新卡卡号
            cardLog.setOldCode(bikeMemberUserCard.getCardCode());//旧卡卡号
            cardLog.setCardNumber(bikeMemberUserCard.getNewCard().getCardNumber());//新卡no号
            cardLog.setOldNumber(bikeMemberUserCard.getCardNumber());//旧卡no号
            cardLog.setOperateType(4);//操作类型 换卡
            cardLog.setCardFee(bikeMemberUserCard.getNewCard().getDeposit());//换卡费
            cardLog.setCardType("1");
            bikeMemberCardLogMapper.insert(cardLog);
            //删除老卡信息
            bikeMemberUserCardMapper.deleteById(bikeMemberUserCard.getId());
            return Result.OK("换卡成功!");
        }

    }


    @Override
    public Result<?> initialize(String icCode) {
        //查询读出的icCode是否存在
        QueryWrapper<BikeMemberUserCard> wrapper = new QueryWrapper<>();
        wrapper.eq("card_code", icCode);
        BikeMemberUserCard userCard = bikeMemberUserCardMapper.selectOne(wrapper);
        //通过ic，查询是否绑定
        if (userCard != null) {
            if (StringUtils.isNotEmpty(userCard.getUserId())) {
                return Result.error("卡已绑定用户！");
            }
            return Result.OK(userCard.getCardCode());
        }
        return creatIcCardCode();
    }


    @Override
    public Result<?> updateByUserId(String userId, String methodType) {
        QueryWrapper<BikeMemberUserCard> userCardQueryWrapper = new QueryWrapper<>();
        userCardQueryWrapper.eq("user_id", userId);
        BikeMemberUserCard memberUserCard = bikeMemberUserCardMapper.selectOne(userCardQueryWrapper);
        if (memberUserCard == null) {
            return Result.error("用户没有卡");
        }
        if (methodType.equals("3")) {
            if (!memberUserCard.getCardStatus().equals("1")) {
                return Result.error("此卡状态非正常，无法挂失！");
            }
            //存入挂失状态
            memberUserCard.setCardStatus(BikeConstant.card_status_lose);
            bikeMemberUserCardMapper.updateById(memberUserCard);
            //卡挂失日志
            BikeMemberCardLog bikeMemberCardLog = new BikeMemberCardLog();
            bikeMemberCardLog.setUserId(userId);
            bikeMemberCardLog.setCardCode(memberUserCard.getCardCode());
            bikeMemberCardLog.setCardNumber(memberUserCard.getCardNumber());
            bikeMemberCardLog.setOperateType(2);
            bikeMemberCardLog.setCardType(memberUserCard.getCardType());
            bikeMemberCardLogMapper.insert(bikeMemberCardLog);
            return Result.OK("挂失成功");

        } else {
            if (!memberUserCard.getCardStatus().equals("2")) {
                return Result.error("此卡状态非挂失，无法解除挂失！");
            }
            //解除挂失状态
            memberUserCard.setCardStatus(BikeConstant.card_status_normal);
            bikeMemberUserCardMapper.updateById(memberUserCard);
            //卡解挂失日志
            BikeMemberCardLog bikeMemberCardLog = new BikeMemberCardLog();
            bikeMemberCardLog.setUserId(userId);
            bikeMemberCardLog.setCardCode(memberUserCard.getCardCode());
            bikeMemberCardLog.setCardNumber(memberUserCard.getCardNumber());
            bikeMemberCardLog.setOperateType(3);
            bikeMemberCardLog.setCardType(memberUserCard.getCardType());
            bikeMemberCardLogMapper.insert(bikeMemberCardLog);
            return Result.OK("解除成功");
        }

    }

    @Override
    public Result<?> adminCard(String id, String icCode, String cardType,String cardNumber) {
        //判断用户是否有卡
        QueryWrapper<BikeMemberUserCard> user = new QueryWrapper<>();
        user.eq("user_id", id);
        BikeMemberUserCard userCard = bikeMemberUserCardMapper.selectOne(user);
        if (userCard != null) {
            return Result.error("用户已有卡，请先退卡");
        }
        //判断卡片
        QueryWrapper<BikeMemberUserCard> wrapper = new QueryWrapper<>();
        wrapper.eq("card_code", icCode);
        BikeMemberUserCard memberUserCard = bikeMemberUserCardMapper.selectOne(wrapper);
        if (memberUserCard == null) {
            BikeMemberUserCard userCard1 = new BikeMemberUserCard();
            userCard1.setCardCode(icCode);
            //如果都没问题
            userCard1.setUserId(id);
            //用户类型为 管理用户
            userCard1.setUserType("2");
            //卡类型由前端控制
            userCard1.setCardType(cardType);
            //卡状态
            userCard1.setCardStatus(BikeConstant.card_status_normal);
            userCard1.setCardNumber(cardNumber);
            //发卡时间
            userCard1.setCardTime(new Date());
            bikeMemberUserCardMapper.insert(userCard1);
        } else {
            if (StringUtils.isNotEmpty(memberUserCard.getUserId())) {
                return Result.error("卡片已绑定");
            }
            //如果都没问题
            memberUserCard.setUserId(id);
            //用户类型为 管理用户
            memberUserCard.setUserType("2");
            //卡类型由前端控制
            memberUserCard.setCardType(cardType);
            //卡状态
            memberUserCard.setCardStatus(BikeConstant.card_status_normal);
            memberUserCard.setCardNumber(cardNumber);
            //发卡时间
            memberUserCard.setCardTime(new Date());
            bikeMemberUserCardMapper.update(memberUserCard, wrapper);
        }
        return Result.OK("发卡成功");
    }

    @Override
    public Result<?> putCard(String id, String type) {
        //判断用户是否有卡
        QueryWrapper<BikeMemberUserCard> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", id);
        BikeMemberUserCard userCard = bikeMemberUserCardMapper.selectOne(wrapper);
        if (userCard == null) {
            return Result.error("未绑定卡");
        }
        //1 挂失
        if (type.equals("1")) {
            if (!userCard.getCardStatus().equals(BikeConstant.card_status_normal)) {
                return Result.error("卡状态非正常");
            } else {
                userCard.setCardStatus(BikeConstant.card_status_lose);
                bikeMemberUserCardMapper.updateById(userCard);
                return Result.OK("挂失成功");
            }

        }
        //2 解挂失
        if (type.equals("2")) {
            if (!userCard.getCardStatus().equals(BikeConstant.card_status_lose)) {
                return Result.error("非挂失状态");
            } else {
                userCard.setCardStatus(BikeConstant.card_status_normal);
                bikeMemberUserCardMapper.updateById(userCard);
                return Result.OK("解挂失成功");
            }
        }
        // 3 退卡
        if (type.equals("3")) {
            if (userCard.getId() == null) {
                return Result.error("用户没有卡");
            }
            bikeMemberUserCardMapper.deleteById(userCard);
            return Result.OK("退卡成功");
        }
        return Result.error("未传type 1 挂失 2 解挂失 3 注销");
    }

    @Override
    public String condition(BikeMemberUserCard bikeMemberUserCard) {


        BikeMemberUserCard userCardData = bikeMemberUserCardMapper.selectById(bikeMemberUserCard);
        QueryWrapper<BikeVehicleOrder> bikeVehicleOrderQueryWrapper = new QueryWrapper<>();
        bikeVehicleOrderQueryWrapper.eq("pick_user", userCardData.getUserId());
        bikeVehicleOrderQueryWrapper.eq("is_pay", BikeConstant.y_n_no);
        BikeVehicleOrder bikeVehicleOrder = bikeVehicleOrderMapper.selectOne(bikeVehicleOrderQueryWrapper);
        if (bikeVehicleOrder != null) {
            return BikeConstant.y_n_no;
        } else {
            return BikeConstant.y_n_yes;
        }
    }

    @Override
    public String checkPinCard(BikeMemberUserCard bikeMemberUserCard) {
        QueryWrapper<BikeVehicleOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("pickUser", bikeMemberUserCard.getUserId());
        BikeVehicleOrder bikeVehicleOrder = bikeVehicleOrderMapper.selectOne(wrapper);
        //判断是否有卡
        if (bikeMemberUserCard.getId() == null) {
            return "用户没有卡";
        }
        //判断用户是否有订单未支付
        if (bikeVehicleOrder != null) {
            if (bikeVehicleOrder.getIsPay().equals(BikeConstant.y_n_no)) {
                return "用户有订单未支付";
            }
        }
        return BikeConstant.y_n_yes;
    }

    @Override
    public Result<?> getKeys() {
        String md5String = MD5Utils.getMD5String(BikeConstant.ic_keys);

        return Result.OK(md5String);
    }

    @Override
    public Result<?> verifyKeys(String keys) {
        String md5String = MD5Utils.getMD5String(BikeConstant.ic_keys);
        if (md5String.equals(keys.toLowerCase())) {
            return Result.OK();
        } else {
            return Result.error("认证错误");
        }
    }

    @Override
    public Result<?> initializeKey(String icCode) {
        //查询读出的icCode是否存在
        QueryWrapper<BikeMemberUserCard> wrapper = new QueryWrapper<>();
        wrapper.eq("card_code", icCode);
        BikeMemberUserCard userCard = bikeMemberUserCardMapper.selectOne(wrapper);
        //判断初始化的卡是否有数据 空为新增  不为空为修改
        if (userCard == null) {
            BikeMemberUserCard newCardData = new BikeMemberUserCard();
            //存入卡code
            newCardData.setCardCode(icCode);
            //存入卡状态
            newCardData.setCardStatus("4");
            bikeMemberUserCardMapper.insert(newCardData);
            return Result.OK();
        } else {
            return Result.OK();
        }
    }


    /**
     * IC卡号生成
     * 16位随机数+12位时间戳+4位校验码
     * 校验码 = 16位随机数+12位时间戳 校验码加密 crc16 rtu 标准 的4位校验码
     * 用4位校验码和16位随机数+12位时间戳 异或， 异或后的值+4位校验码 转hex就是卡号
     */
    @Override
    public Result<?> creatIcCardCode() {
        //获取12位时间戳
        long time = new Date().getTime();
        byte[] a = new byte[16];
        for (int i = 0; i < 8; i++) {
            int b = (int) (Math.random() * 255);
            a[i] = (byte) b;
        }
        for (int i = 8; i < 14; i++) {
            a[i] = (byte) (time >> i - 8 % 0xff);
        }
        int crc2 = MD5Utils.getCRC(a, 14);

        a[14] = (byte) (crc2 >> 8 & 0xff);
        a[15] = (byte) (crc2 & 0xff);
        for (int i = 0; i < 7; i++) {
            a[i * 2] ^= a[14];
            a[i * 2 + 1] ^= a[15];
        }
        String cardCode = MD5Utils.bytes2HexString(a);
        return Result.OK(cardCode);
    }

    @Override
    public void setUserCard(BikeMemberUser bikeMemberUser) {
        if (StringUtils.isNotEmpty(bikeMemberUser.getCardCode())) {
            BikeMemberUserCard userCard = bikeMemberUserCardMapper.selectOne(new QueryWrapper<BikeMemberUserCard>().eq("card_code", bikeMemberUser.getCardCode()));
            if (userCard != null) {
                userCard.setUserId(bikeMemberUser.getId());
                userCard.setCardStatus(BikeConstant.card_status_normal);
                userCard.setUserType(BikeConstant.member_type_user);
                //设置卡类型  1 普通 2 管理 3 运维
                userCard.setCardType("1");
                bikeMemberUserCardMapper.updateById(userCard);
            } else {
                BikeMemberUserCard memberUserCard = new BikeMemberUserCard();
                memberUserCard.setCardCode(bikeMemberUser.getCardCode());
                memberUserCard.setUserId(bikeMemberUser.getId());
                memberUserCard.setCardStatus(BikeConstant.card_status_normal);
                memberUserCard.setUserType(BikeConstant.member_type_user);
                //设置卡类型  1 普通 2 管理 3 运维
                memberUserCard.setCardType("1");
                bikeMemberUserCardMapper.insert(memberUserCard);
            }
        }

    }

    /**
     * 退卡日志
     */
    @Override
    public void returnTheCard(BikeMemberUserCard bikeMemberUserCard) {
        BikeMemberUser memberUser = bikeMemberUserMapper.selectById(bikeMemberUserCard.getUserId());
        BikeMemberUserCard userCard = bikeMemberUserCardMapper.selectById(bikeMemberUserCard.getId());
        //退卡日志
        BikeMemberCardLog bikeMemberCardLog = new BikeMemberCardLog();
        bikeMemberCardLog.setUserId(userCard.getUserId());//用户id
        bikeMemberCardLog.setCardCode(userCard.getCardCode());//卡号
        bikeMemberCardLog.setCardNumber(userCard.getCardNumber());//卡no号
        bikeMemberCardLog.setOperateType(5);//类型为退卡
        bikeMemberCardLog.setCardDeposit(userCard.getCardFee());//押金
        bikeMemberCardLog.setCardFee(bikeMemberUserCard.getDeposit());//卡费
        bikeMemberCardLog.setAccount(memberUser.getBalance());//发生额 余额+押金
        bikeMemberCardLog.setCardType(userCard.getCardType());
        bikeMemberCardLogMapper.insert(bikeMemberCardLog);
        //退卡
        bikeMemberUserCardMapper.deleteById(userCard);
        //退余额
        memberUser.setBalance(new BigDecimal(0));
        bikeMemberUserMapper.updateById(memberUser);
    }

    @Override
    public boolean checkUserCardFree(BikeMemberUserCard bikeMemberUserCard) {
        long time = new Date().getTime()-7257600000L;
        Date date = new Date(time);
        Integer selectCount = bikeMemberCardLogMapper.selectCount(
                new QueryWrapper<BikeMemberCardLog>()
                        .eq("user_id", bikeMemberUserCard.getUserId())
                        .eq("card_type", "1").ge("create_time", date)
        );
        return selectCount==0 ;
    }
}
